import { defineStore } from "pinia";
import request from '@/utils/request'
import { ApiRes, CategoryItem, TopCategory } from '@/types/data'
import { topCategory } from '../constants'

// 通过 map 映射, 将常量字符串数组转成对象数组
const defaultCategory = topCategory.map(name => ({ name }))

// 定义子模块并导出
// 参数1: 模块名, 不能和其他子模块重名
// 参数2: 配置项(state / actions / getters)
export default defineStore('category', {
  state: () => ({
    list: defaultCategory as CategoryItem[],
    topCategory: {} as TopCategory
  }),
  actions: {
    async getAllCategory() {
      // type CategoryItem = {}
      // type CategoryRes = {
      //   msg: string,
      //   code: string,
      //   result: CategoryItem[]
      // }
      // type BannerRes = {
      //   msg: string,
      //   code: string,
      //   result: BannerItem[]
      // }
      // const res = await request.get<ApiRes<BannerItem[]>>('/home/banner')
      const res = await request.get<ApiRes<CategoryItem[]>>('/home/category/head')
      // console.log(res)
      this.list = res.data.result
    },
    // 根据 id 获取当前顶级分类的数据
    async getTopCategory(id: string) {
      const res = await request.get<ApiRes<TopCategory>>('/category', {
        params: {
          id
        }
      })
      // console.log(res)
      this.topCategory = res.data.result
    }
  },
  getters: {}
})